#include "directory.h"

#include <string.h>
#include <stdlib.h>

#ifdef _WIN32

#include <Windows.h>

static void set_working_directory(const char *path) {
	SetCurrentDirectory(path);
}

static void go_to_process_directory() {
	HMODULE hModule = GetModuleHandleW(NULL);
	CHAR path[MAX_PATH];
	GetModuleFileNameA(hModule, path, MAX_PATH);

	dir_set_file(path);
}

static char *get_working_directory() {
	char *new_str = malloc(sizeof(char) * MAX_PATH);
	GetCurrentDirectory(MAX_PATH, new_str);
	return new_str;
}

#endif

void dir_set_process() {
	go_to_process_directory();
}

void dir_set(const char *path) {
	set_working_directory(path);
}

void dir_set_file(const char *path) {
	char *actual_path;

	size_t full_length = strlen(path);
	actual_path = malloc(sizeof(char) * (full_length + 1));

	strcpy(actual_path, path);

	size_t i = full_length - 1;
	while (i > 0) {
		if (actual_path[i] == '/' || actual_path[i] == '\\') break;
		actual_path[i] = '\0';
		--i;
	}

	actual_path[i--] = '\0';

	if(i != 0)
		set_working_directory(actual_path);

	free(actual_path);
}

char *dir_isolate_file(const char *path) {
	size_t length = strlen(path);
	size_t index = length - 1;

	while (index > 0) {
		if (path[index] == '/' || path[index] == '\\') {
			break;
		}
		--index;
	}
	if (path[index] == '/' || path[index] == '\\') ++index;

	char *new_string = malloc(sizeof(char) * (length - index + 1));

	strcpy(new_string, path + index);

	return new_string;
}

char *dir_get() {
	return get_working_directory();
}